<template>
  <div class="amap-container">
    <div id="map-container" ref="mapContainer" class="map-container"></div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="map-loading">
      <div class="loading-spinner"></div>
      <p>地图加载中...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="map-error">
      <p>❌ {{ error }}</p>
      <button @click="initMap" class="retry-btn">重新加载</button>
    </div>

    <!-- 地图控件 -->
    <div v-if="!loading && !error" class="map-controls">
      <button class="control-btn" @click="locateUser" title="定位">
        <span class="control-icon">📍</span>
      </button>
      <button class="control-btn" @click="toggleCluster" :title="useCluster ? '关闭聚合' : '开启聚合'">
        <span class="control-icon">{{ useCluster ? '🔗' : '🔘' }}</span>
      </button>
      <button class="control-btn" @click="zoomIn" title="放大">
        <span class="control-icon">➕</span>
      </button>
      <button class="control-btn" @click="zoomOut" title="缩小">
        <span class="control-icon">➖</span>
      </button>
    </div>

    <!-- 信息窗口 -->
    <div v-if="infoWindow.show" class="info-window" :style="infoWindow.style">
      <div class="info-header">
        <h4>{{ infoWindow.station?.stationName }}</h4>
        <button class="close-btn" @click="closeInfoWindow">×</button>
      </div>
      <div class="info-content">
        <p class="address">{{ infoWindow.station?.address }}</p>
        <div class="status-info">
          <span class="status-badge" :class="getStatusClass(infoWindow.station)">
            {{ getStatusText(infoWindow.station) }}
          </span>
          <span class="distance">{{ store.formatDistance(infoWindow.station?.distance || 0) }}</span>
        </div>
        <div class="charger-info">
          <span>快充: {{ infoWindow.station?.quickAvailableNum }}/{{ infoWindow.station?.quickChargeNum }}</span>
          <span>慢充: {{ infoWindow.station?.slowAvailableNum }}/{{ infoWindow.station?.slowChargeNum }}</span>
        </div>
        <div class="price">¥{{ infoWindow.station?.totalCostPrice }}/度</div>
        <div class="action-buttons">
          <button class="nav-btn" @click="startNavigation(infoWindow.station)">导航</button>
          <button class="detail-btn" @click="showStationDetail(infoWindow.station)">详情</button>
          <button class="amap-btn" @click="openExternalAMap(infoWindow.station)">打开高德</button>
        </div>
      </div>
    </div>

    <!-- 路线信息面板 -->
    <div v-if="routeInfo.show" class="route-info-panel">
      <div class="route-header">
        <h4>导航路线</h4>
        <button class="close-btn" @click="routeInfo.show = false">×</button>
      </div>
      <div class="route-content">
        <div class="route-detail">
          <div class="route-item">
            <span class="label">目的地:</span>
            <span class="value">{{ routeInfo.toStation?.stationName }}</span>
          </div>
          <div class="route-item">
            <span class="label">距离:</span>
            <span class="value">{{ routeInfo.distance }}</span>
          </div>
          <div class="route-item">
            <span class="label">预计时间:</span>
            <span class="value">{{ routeInfo.duration }}</span>
          </div>
        </div>
        <button class="start-nav-btn" @click="confirmRouteNavigation">开始导航</button>
      </div>
    </div>

    <!-- 充电站详情页面 -->
    <StationDetail 
      v-if="showDetail && detailStation"
      :station="detailStation"
      @close="closeDetail"
      @navigate="handleDetailNavigate"
      @startCharge="handleStartCharge"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { useStationsStore } from '@/stores/station'
import StationDetail from '../StationDetail/StationDetail.vue'

const store = useStationsStore()

// 定义组件事件
const emit = defineEmits(['startCharge'])

// 响应式数据
const mapContainer = ref<HTMLElement>()
const map = ref<any>(null)
const AMap = ref<any>(null)
const loading = ref(false)
const error = ref<string>('')
const markers = ref<any[]>([])
const cluster = ref<any>(null)
const useCluster = ref(false)
const userLocationMarker = ref<any>(null)





// 信息窗口
const infoWindow = ref({
  show: false,
  station: null as any,
  style: {
    left: '0px',
    top: '0px'
  }
})

// 路线信息
const routeInfo = ref({
  show: false,
  toStation: null as any,
  distance: '',
  duration: ''
})

// 详情页面
const showDetail = ref(false)
const detailStation = ref(null)

// 配置
const mapConfig = {
  key: import.meta.env.VITE_AMAP_API_KEY || '9d87e0914c9e4df58ebf6b173b76a362',
  securityCode: import.meta.env.VITE_AMAP_SECURITY_CODE || '853ebdbc8a37cf392de91b7bc1d7acf8',
  center: [104.06, 30.67] as [number, number], // 成都中心
  zoom: 12
}

// 安全配置
if (mapConfig.securityCode) {
  (window as any)._AMapSecurityConfig = {
    securityJsCode: mapConfig.securityCode
  }
}

// 初始化地图
const initMap = async () => {
  console.log('🗺️ 开始初始化地图...')
  
  if (!mapContainer.value) {
    await nextTick()
  }
  
  if (!mapContainer.value) {
    error.value = '地图容器未找到'
    return
  }

  loading.value = true
  error.value = ''
  
  try {
    // 加载高德地图API，包含聚合插件
    AMap.value = await AMapLoader.load({
      key: mapConfig.key,
      version: '2.0',
      plugins: [
        'AMap.ToolBar',
        'AMap.Scale', 
        'AMap.Geolocation',
        'AMap.Driving',
        'AMap.MarkerClusterer'
      ]
    })

    console.log('✅ 高德地图API加载成功')

    // 创建地图实例
  map.value = new AMap.value.Map('map-container', {
    viewMode: '2D',
    zoom: mapConfig.zoom,
    center: mapConfig.center,
    mapStyle: 'amap://styles/normal',
    // 添加性能优化配置
    optimizePanAnimation: true,
    optimizePitchAnimation: true,
    autoRotation: false,
    defaultCursor: 'default'
  })

    console.log('✅ 地图实例创建成功')

    // 添加控件
    addMapControls()
    
    // 绑定地图事件
    bindMapEvents()
    
    // 加载充电站数据
    if (store.stations.length === 0) {
      console.log('🔄 加载充电站数据...')
      await store.loadStations()
    }

    // 显示标记点
    setTimeout(() => {
      console.log('✅ 地图渲染完成')
      loading.value = false
      
      // 添加自定义样式
      addCustomStyles()
      
      // 创建标记 - 直接显示单个充电桩点
      if (store.stations && store.stations.length > 0) {
        console.log('📍 直接显示单个充电桩点')
        createSingleMarkers()
      } else {
        console.log('⚠️ 暂无充电站数据')
      }
    }, 500)
    
    // 添加自定义样式函数
    const addCustomStyles = () => {
      // 检查是否已存在样式
      const existingStyle = document.getElementById('charging-map-custom-styles')
      if (existingStyle) {
        existingStyle.remove()
      }
      
      const style = document.createElement('style')
      style.id = 'charging-map-custom-styles'
      style.innerHTML = `
        /* 脉动动画效果 */
        @keyframes pulse-free {
          0% {
            box-shadow: 0 0 0 0 rgba(82, 196, 26, 0.7);
            transform: scale(1);
          }
          70% {
            box-shadow: 0 0 0 12px rgba(82, 196, 26, 0);
            transform: scale(1.05);
          }
          100% {
            box-shadow: 0 0 0 0 rgba(82, 196, 26, 0);
            transform: scale(1);
          }
        }
        
        @keyframes pulse-busy {
          0% {
            box-shadow: 0 0 0 0 rgba(250, 140, 22, 0.7);
            transform: scale(1);
          }
          70% {
            box-shadow: 0 0 0 15px rgba(250, 140, 22, 0);
            transform: scale(1.05);
          }
          100% {
            box-shadow: 0 0 0 0 rgba(250, 140, 22, 0);
            transform: scale(1);
          }
        }
        
        /* 状态变化过渡动画 */
        .custom-marker[data-status="free"],
        .custom-marker[data-status="busy"],
        .custom-marker[data-status="maintenance"] {
          transition: background-color 0.5s ease, transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        /* 加载状态样式 */
        .loading-indicator {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          background: rgba(255, 255, 255, 0.9);
          padding: 16px 24px;
          border-radius: 8px;
          box-shadow: 0 4px 16px rgba(0,0,0,0.1);
          font-size: 14px;
          color: #666;
          display: flex;
          align-items: center;
          gap: 8px;
        }
        
        .loading-indicator::before {
          content: '';
          width: 16px;
          height: 16px;
          border: 2px solid #f0f0f0;
          border-top: 2px solid #1890ff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `
      
      document.head.appendChild(style)
    }
    
  } catch (err: any) {
    console.error('❌ 高德地图加载失败:', err)
    error.value = getErrorMessage(err)
    loading.value = false
  }
}

// 获取错误信息
const getErrorMessage = (err: any): string => {
  if (err.message?.includes('KEY')) {
    return '地图API密钥配置错误'
  } else if (err.message?.includes('security')) {
    return '安全密钥验证失败'
  } else if (err.message?.includes('network')) {
    return '网络连接失败，请检查网络设置'
  } else {
    return `地图加载失败: ${err.message || '未知错误'}`
  }
}

// 添加地图控件
const addMapControls = () => {
  if (!map.value || !AMap.value) return
  
  // 比例尺
  map.value.addControl(new AMap.value.Scale({
    position: 'LB'
  }))
}

// 绑定地图事件
const bindMapEvents = () => {
  if (!map.value) return
  
  // 地图点击事件 - 点击空白处关闭信息窗口
  map.value.on('click', (ev: any) => {
    if (!ev.originalEvent.target.closest('.custom-marker') && 
        !ev.originalEvent.target.closest('.amap-marker-cluster')) {
      closeInfoWindow()
    }
  })
  
  // 地图缩放事件 - 优化性能
  map.value.on('zoomend', () => {
    if (!store.stations || store.stations.length === 0) return
    
    const zoom = map.value.getZoom()
    const previousZoom = lastRenderZoom || zoom
    
    console.log(`� 地图缩放至级别: ${zoom}, 变化: ${previousZoom < zoom ? '放大' : '缩小'}`)
    
    // 如果缩放级别变化不大，避免重新渲染
    if (Math.abs(zoom - previousZoom) < 1) {
      console.log('📌 缩放级别变化小，跳过重新渲染')
      return
    }
    
    // 根据缩放级别和站点数量智能选择显示模式
    // const totalStations = store.stations.length // 暂时注释掉未使用的变量
    
    // 直接显示单个充电桩点，不考虑缩放级别
    console.log('🔍 地图缩放，直接显示单个充电桩点')
    createSingleMarkers()
  })
  
  // 地图拖动事件 - 支持拖动查看不同区域
  map.value.on('dragend', () => {
    if (!store.stations) return
    
    const zoom = map.value.getZoom()
    console.log('🗺️ 地图拖动完成')
    // 获取当前地图范围
    const bounds = map.value.getBounds()
    console.log(`🗺️ 当前地图范围: ${bounds.toString()}`)
    
    // 仅在显示单个标记模式下更新视野
    if (zoom >= 15 && !isRendering) {
      console.log('🗺️  地图移动，更新视野内标记')
      // 使用防抖处理减少渲染次数
      if (markersBatchRenderTimer) {
        clearTimeout(markersBatchRenderTimer)
      }
      
      markersBatchRenderTimer = window.setTimeout(() => {
        createSingleMarkers()
      }, 150)
    }
  })
  
  // 地图加载完成事件
  map.value.on('complete', () => {
    console.log('✅ 地图完全加载完成')
    // 确保标记正确显示
    if (store.stations && store.stations.length > 0) {
      createStationMarkers()
    }
  })
}

// Spiderfy展开模式 - 当聚合点数量较小时使用
// let spiderfyMode = false // 注释掉未使用的变量
let spiderfyMarkers: any[] = []

// 创建聚合标记
const createClusterMarkers = () => {
  if (!map.value || !AMap.value) return
  
  console.log('🔗 创建聚合标记...')
  
  // 清理现有标记和聚合
  clearMarkers()
  if (cluster.value) {
    cluster.value.setMap(null)
    cluster.value = null
  }
  
  // 清理之前的Spiderfy标记
  clearSpiderfyMarkers()
  
  // 对大量数据进行分批处理
  const batchSize = 500
  const batches = []
  
  for (let i = 0; i < store.stations.length; i += batchSize) {
    batches.push(store.stations.slice(i, i + batchSize))
  }
  
  let allMarkers: any[] = []
  
  batches.forEach((batch) => {
    const batchMarkers = batch.map((station: any) => {
      return new AMap.value.Marker({
        position: [station.lng, station.lat],
        content: createMarkerContent(station),
        title: station.stationName,
        extData: station,
        zooms: [14, 18] // 控制标记显示的缩放级别范围
      })
    })
    
    allMarkers = [...allMarkers, ...batchMarkers]
  })
  
  // 创建聚合器
  cluster.value = new AMap.value.MarkerClusterer(map.value, allMarkers, {
    gridSize: 80,
    maxZoom: 18,
    averageCenter: true,
    minClusterSize: 3, // 最小聚合数量
    styles: [
      {
        url: '',
        size: new AMap.value.Size(40, 40),
        offset: new AMap.value.Pixel(-20, -20),
        textSize: 12
      },
      {
        url: '',
        size: new AMap.value.Size(50, 50),
        offset: new AMap.value.Pixel(-25, -25),
        textSize: 14
      },
      {
        url: '',
        size: new AMap.value.Size(60, 60),
        offset: new AMap.value.Pixel(-30, -30),
        textSize: 16
      }
    ],
    renderClusterMarker: (context: any) => {
      const count = context.count
      let size = 40
      let color = '#1890ff'
      
      // 根据聚合数量使用不同样式，符合阈值要求
      if (count > 200) {
        size = 60
        color = '#ff4d4f'
      } else if (count > 100) {
        size = 55
        color = '#ff7a45'
      } else if (count > 50) {
        size = 50
        color = '#fa8c16'
      } else if (count > 10) {
        size = 45
        color = '#52c41a'
      }
      
      const div = document.createElement('div')
      div.style.cssText = `
        width: ${size}px;
        height: ${size}px;
        background: ${color};
        border: 3px solid white;
        border-radius: 50%;
        color: white;
        font-size: ${size < 50 ? 12 : 14}px;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 8px rgba(0,0,0,0.3);
        font-weight: bold;
        cursor: pointer;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
      `
      div.innerHTML = count > 999 ? `${Math.floor(count/1000)}k` : count
      
      // 添加悬停效果
      div.addEventListener('mouseover', () => {
        div.style.transform = 'scale(1.1)'
        div.style.boxShadow = '0 4px 12px rgba(0,0,0,0.4)'
      })
      
      div.addEventListener('mouseout', () => {
        div.style.transform = 'scale(1)'
        div.style.boxShadow = '0 2px 8px rgba(0,0,0,0.3)'
      })
      
      context.marker.setOffset(new AMap.value.Pixel(-size/2, -size/2))
      context.marker.setContent(div)
    }
  })
  
  // 绑定聚合点击事件
  cluster.value.on('click', (event: any) => {
    const markers = event.clusterData.markers || []
    
    // 关闭之前的spiderfy模式
    clearSpiderfyMarkers()
    
    if (markers.length === 1) {
      // 单个标记，显示信息窗口
      const station = markers[0].getExtData()
      showInfoWindow(station, event.lnglat)
    } else if (markers.length <= 20 && map.value.getZoom() >= 16) {
      // 数量较少时使用spiderfy模式展开
      console.log(`🕷️ 使用Spiderfy模式展开${markers.length}个标记`)
      showSpiderfyMarkers(markers, event.lnglat)
    } else {
      // 聚合点，放大到该区域
      const zoom = Math.min(map.value.getZoom() + 2, 18)
      map.value.setZoomAndCenter(zoom, event.lnglat)
    }
  })
}

// 清理Spiderfy标记
const clearSpiderfyMarkers = () => {
  spiderfyMarkers.forEach(marker => {
    if (marker && map.value) {
      map.value.remove(marker)
    }
  })
  spiderfyMarkers = []
  // spiderfyMode = false // 注释掉未定义变量的引用
}

// Spiderfy展开显示标记
const showSpiderfyMarkers = (markers: any[], center: any) => {
  if (!map.value || !AMap.value || markers.length === 0) return
  
  console.log(`🕷️ 使用Spiderfy模式展开${markers.length}个标记`)
  
  // 关闭之前的spiderfy模式
  clearSpiderfyMarkers()
  
  const radius = 60 // 展开半径
  const newMarkers: any[] = []
  
  // 计算每个标记的位置
  markers.forEach((marker, index) => {
    const angle = (index * 2 * Math.PI) / markers.length
    const offsetX = radius * Math.cos(angle)
    const offsetY = radius * Math.sin(angle)
    
    // 计算新位置
    const newPosition = map.value.lngLatToContainer(center)
    newPosition.setX(newPosition.getX() + offsetX)
    newPosition.setY(newPosition.getY() + offsetY)
    const newLngLat = map.value.containerToLngLat(newPosition)
    
    // 创建线条连接到中心点
    const line = new AMap.value.Polyline({
      path: [center, newLngLat],
      strokeColor: '#999',
      strokeOpacity: 0.6,
      strokeWeight: 2,
      zIndex: 100 // 设置z-index确保线条在标记下方
    })
    newMarkers.push(line)
    
    // 创建新标记
    const station = marker.getExtData()
    const newMarker = new AMap.value.Marker({
      position: newLngLat,
      content: createMarkerContent(station),
      title: station.stationName,
      extData: station,
      zIndex: 200 // 设置z-index确保标记在线条上方
    })
    
    // 添加点击事件
    newMarker.on('click', (e: any) => {
      showInfoWindow(station, e.lnglat)
    })
    
    newMarkers.push(newMarker)
  })
  
  // 批量添加到地图，提高性能
  if (map.value && newMarkers.length > 0) {
    map.value.add(newMarkers)
  }
  
  // 保存到数组以便后续清理
  spiderfyMarkers = newMarkers
}

// 标记渲染性能优化相关
const MAX_VISIBLE_MARKERS = 1000 // 最大同时显示标记数
let markersBatchRenderTimer: number | null = null
let isRendering = false
let lastRenderZoom = 0
let visibleMarkersMap = new Map() // 用于跟踪已显示的标记

// 创建单个标记
const createSingleMarkers = () => {
  if (!map.value || !AMap.value || !store.stations || store.stations.length === 0 || isRendering) return
  
  // 防抖处理，避免频繁渲染
  if (markersBatchRenderTimer) {
    clearTimeout(markersBatchRenderTimer)
  }
  
  markersBatchRenderTimer = window.setTimeout(() => {
    console.log('📍 创建单个标记...')
    isRendering = true
    
    // 清理现有标记
    clearMarkers()
    if (cluster.value) {
      cluster.value.setMap(null)
      cluster.value = null
    }
    
    // 获取当前地图视野范围和缩放级别
    const bounds = map.value.getBounds()
    const currentZoom = map.value.getZoom()
    
    // 过滤在视野范围内的站点
    const visibleStations = store.stations.filter((station: any) => {
      return bounds.contains([station.lng, station.lat])
    })
    
    // 如果标记数量过多，只显示部分标记
    const stationsToShow = visibleStations.length > MAX_VISIBLE_MARKERS 
      ? visibleStations.slice(0, MAX_VISIBLE_MARKERS) 
      : visibleStations
    
    console.log(`👀 当前视野内充电站: ${visibleStations.length}, 显示: ${stationsToShow.length} 个`)
    
    // 记录需要移除的标记ID
    const markersToRemove = new Set(visibleMarkersMap.keys())
    
    // 批量创建/更新标记
    const markersToAdd: any[] = []
    const batchSize = 100
    
    // 分批处理标记创建
    const processBatch = (startIndex: number) => {
      if (startIndex >= stationsToShow.length) {
        // 移除不在视野内的标记
        markersToRemove.forEach(id => {
          const marker = visibleMarkersMap.get(id)
          if (marker && map.value) {
            map.value.remove(marker)
          }
          visibleMarkersMap.delete(id)
        })
        
        // 将新标记添加到地图
        if (markersToAdd.length > 0) {
          map.value.add(markersToAdd)
          // 同时更新markers.value数组，确保标记被正确管理
          markers.value = [...markers.value, ...markersToAdd]
        }
        
        console.log(`✅ 标记渲染完成，当前显示: ${visibleMarkersMap.size} 个`)
        isRendering = false
        lastRenderZoom = currentZoom
        return
      }
      
      // 处理当前批次
      const endIndex = Math.min(startIndex + batchSize, stationsToShow.length)
      const batch = stationsToShow.slice(startIndex, endIndex)
      
      batch.forEach((station: any) => {
        const stationId = station.stationId || `${station.lng}-${station.lat}`
        
        // 标记此站点不需要移除
        markersToRemove.delete(stationId)
        
        // 如果标记已存在，更新它
        if (visibleMarkersMap.has(stationId)) {
          const existingMarker = visibleMarkersMap.get(stationId)
          const newContent = createMarkerContent(station)
          existingMarker.setContent(newContent)
        } else {
          // 创建新标记
          const marker = new AMap.value.Marker({
            position: [station.lng, station.lat],
            content: createMarkerContent(station),
            title: station.stationName,
            extData: station,
            animateMove: true
          })
          
          // 绑定点击事件
          marker.on('click', (event: any) => {
            const stationData = event.target.getExtData()
            showInfoWindow(stationData, event.lnglat)
          })
          
          // 添加到待添加列表
          markersToAdd.push(marker)
          visibleMarkersMap.set(stationId, marker)
        }
      })
      
      // 继续处理下一批
      setTimeout(() => processBatch(endIndex), 0)
    }
    
    // 开始分批处理
    processBatch(0)
  }, 100) // 100ms防抖延迟
}

// 切换聚合模式
const toggleCluster = () => {
  useCluster.value = !useCluster.value
  console.log(`🔄 切换聚合模式: ${useCluster.value ? '聚合' : '普通'}`)
  createStationMarkers()
}

// 创建标记
const createStationMarkers = () => {
  if (!map.value || !AMap.value || !store.stations || store.stations.length === 0) {
    console.log('⚠️ 没有充电站数据可显示')
    return
  }
  
  console.log(`🔗 创建${store.stations.length}个充电站标记...`)
  
  if (useCluster.value) {
    createClusterMarkers()
  } else {
    createSingleMarkers()
  }
}

// 显示信息窗口
const showInfoWindow = (station: any, lnglat: any) => {
  if (!map.value) return
  
  console.log(`🔍 显示充电站信息: ${station.stationName}`)
  
  const pixel = map.value.lngLatToContainer(lnglat)
  infoWindow.value = {
    show: true,
    station,
    style: {
      left: `${Math.min(pixel.getX() - 150, mapContainer.value?.clientWidth ? mapContainer.value.clientWidth - 320 : 500)}px`,
      top: `${Math.max(0, pixel.getY() - 200)}px`
    }
  }
  
  store.setSelectedStation(station)
}

// 关闭信息窗口
const closeInfoWindow = () => {
  infoWindow.value.show = false
  store.setSelectedStation(null)
}

// 显示站点详情
const showStationDetail = (station: any) => {
  detailStation.value = station
  showDetail.value = true
  closeInfoWindow()
  console.log('📋 显示站点详情:', station.stationName)
}

// 关闭详情页面
const closeDetail = () => {
  showDetail.value = false
  detailStation.value = null
}

// 处理详情页面中的导航
const handleDetailNavigate = (station: any) => {
  startNavigation(station)
  closeDetail()
}

// 处理详情页面中的开始充电
const handleStartCharge = (station: any) => {
  console.log('⚡ 开始充电流程:', station.stationName)
  // 向父组件发送开始充电事件
  emit('startCharge', station)
  closeDetail()
}

// 导航路径
const navigationPath = ref<any>(null)

// 开始导航
const startNavigation = (station: any) => {
  if (!map.value || !station || !AMap.value) return
  
  // 导航起点（当前位置）
  const startPoint = store.userLocation || [104.06, 30.67] // 默认起点
  // 导航终点（充电站位置）
  const endPoint = [station.lng, station.lat]
  
  // 清理之前的路线
  if (navigationPath.value) {
    map.value.remove(navigationPath.value)
    navigationPath.value = null
  }
  
  console.log(`🗺️ 导航: 从 [${startPoint}] 到 [${endPoint}]`)
  
  // 移除之前的导航面板
  const oldPanel = document.getElementById('navigation-panel')
  if (oldPanel) {
    oldPanel.remove()
  }
  
  // 创建导航面板
  const navPanel = document.createElement('div')
  navPanel.id = 'navigation-panel'
  navPanel.style.cssText = `
    position: absolute;
    bottom: 20px;
    left: 20px;
    width: 300px;
    height: 200px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.15);
    padding: 12px;
    z-index: 1000;
    overflow-y: auto;
  `
  navPanel.innerHTML = `<h3 style="margin-top:0; color:#1890ff;">导航信息</h3><div id="panel" style="font-size:14px;">正在规划路线...</div>`
  mapContainer.value?.appendChild(navPanel)
  
  // 使用高德地图驾车导航API
  const driving = new AMap.value.Driving({
    map: map.value,
    panel: 'panel', // 显示导航面板
    lang: 'zh_cn',
    policy: AMap.value.DrivingPolicy.LEAST_DISTANCE, // 最短距离策略
    showTraffic: true // 显示实时交通状况
  })
  
  // 计算并显示路线
  driving.search(startPoint, endPoint, function(status: string, result: any) {
    if (status === 'complete') {
      console.log('✅ 导航计算成功')
      navigationPath.value = driving
      
      // 获取路线信息
      const route = result.routes[0]
      const distance = (route.distance / 1000).toFixed(2) // 转换为千米
      const duration = Math.ceil(route.duration / 60) // 转换为分钟
      
      // 在面板中添加路线摘要信息
      const panel = document.getElementById('panel')
      if (panel) {
        const summary = document.createElement('div')
        summary.style.cssText = `
          margin-top: 10px;
          padding: 10px;
          background: #f5f5f5;
          border-radius: 4px;
          font-weight: 500;
        `
        
        // 添加打开高德地图的按钮
        const openAMapBtn = document.createElement('button')
        openAMapBtn.textContent = '打开高德地图'
        openAMapBtn.style.cssText = `
          width: 100%;
          padding: 8px 16px;
          background: #1890ff;
          color: white;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          margin-top: 8px;
          font-size: 14px;
          font-weight: 500;
        `
        openAMapBtn.onclick = () => {
          const amapUrl = `https://uri.amap.com/navigation?to=${station.lng},${station.lat}&callnative=1`
          window.open(amapUrl, '_blank')
          console.log('🔗 已打开外部高德地图导航')
        }
        
        summary.innerHTML = `
          <div>总距离: <span style="color:#1890ff;">${distance} km</span></div>
          <div>预计时间: <span style="color:#1890ff;">${duration} 分钟</span></div>
          <div>充电站: <span style="color:#1890ff;">${station.stationName}</span></div>
        `
        summary.appendChild(openAMapBtn)
        panel.prepend(summary)
      }
      
      // 显示终点标记
      const endMarker = new AMap.value.Marker({
        position: endPoint,
        content: `
          <div style="
            width: 24px;
            height: 24px;
            background: #52c41a;
            border: 3px solid white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
          ">E</div>
        `,
        offset: new AMap.value.Pixel(-12, -12),
        title: station.stationName
      })
      
      map.value.add(endMarker)
      
      // 调整地图视野以显示整个路线
      map.value.setFitView([startPoint, endPoint], false, [30, 30])
    } else {
      console.error('❌ 导航计算失败:', result)
      alert('导航计算失败，请重试')
    }
  })
  
  // 添加清除导航按钮
  const clearNavBtn = document.createElement('button')
  clearNavBtn.textContent = '清除导航'
  clearNavBtn.style.cssText = `
    position: absolute;
    bottom: 230px;
    left: 20px;
    padding: 8px 16px;
    background: #ff4d4f;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    z-index: 1001;
  `
  clearNavBtn.onclick = () => {
    if (navigationPath.value) {
      map.value.remove(navigationPath.value)
      navigationPath.value = null
    }
    navPanel.remove()
    clearNavBtn.remove()
    console.log('🗑️ 已清除导航路线')
  }
  mapContainer.value?.appendChild(clearNavBtn)
}

// 确认路线导航
const confirmRouteNavigation = () => {
  console.log('✅ 确认导航到:', routeInfo.value.toStation.stationName)
  // 调用真实导航API
  const amapUrl = `https://uri.amap.com/navigation?to=${routeInfo.value.toStation.lng},${routeInfo.value.toStation.lat}&callnative=1`
  window.open(amapUrl, '_blank')
  routeInfo.value.show = false
  closeInfoWindow()
}

// 打开外部高德地图导航
const openExternalAMap = (station: any) => {
  if (!station) return
  
  console.log('🌏 打开外部高德地图导航到:', station.stationName)
  // 构造高德地图导航链接
  const amapUrl = `https://uri.amap.com/navigation?to=${station.lng},${station.lat}&callnative=1`
  window.open(amapUrl, '_blank')
  
  // 可以选择是否关闭信息窗口
  // closeInfoWindow()
}

// 创建标记内容（带动画效果）
const createMarkerContent = (station: any) => {
  const status = store.getStationStatus(station)
  const availableCount = store.getAvailableCount(station)
  const totalCount = store.getTotalCount(station)
  
  const statusConfig = {
    free: { color: '#52c41a', class: 'free' },
    busy: { color: '#fa8c16', class: 'busy' }, 
    maintenance: { color: '#f5222d', class: 'maintenance' }
  }
  
  const config = statusConfig[status] || statusConfig.free
  const ratio = totalCount > 0 ? availableCount / totalCount : 0
  const size = ratio > 0.7 ? 44 : ratio > 0.3 ? 40 : 36
  
  // 添加脉动效果样式和过渡动画
  let pulseStyle = ''
  if (status === 'free') {
    pulseStyle = `animation: pulse-free 2s infinite;`
  } else if (status === 'busy') {
    pulseStyle = `animation: pulse-busy 3s infinite;`
  } else if (status === 'maintenance') {
    pulseStyle = `animation: pulse-maintenance 2.5s infinite;`
  }
  
  return `
    <div class="custom-marker ${config.class}" data-station-id="${station.stationId}" data-status="${status}" style="
      width: ${size}px;
      height: ${size}px;
      background: ${config.color};
      border: 3px solid white;
      border-radius: 50%;
      color: white;
      font-size: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 8px rgba(0,0,0,0.3);
      ${pulseStyle}
      font-weight: bold;
      cursor: pointer;
      transition: all 0.5s ease-in-out; /* 平滑过渡动画 */
      position: relative;
      will-change: background-color; /* 优化动画性能 */
    " title="${station.stationName}">
      <span style="
        transition: opacity 0.3s ease;
      ">${availableCount}/${totalCount}</span>
      
      <!-- 状态指示器边框 -->
      <div style="
        position: absolute;
        top: -4px;
        left: -4px;
        right: -4px;
        bottom: -4px;
        border-radius: 50%;
        border: 2px solid ${config.color};
        opacity: 0.6;
        pointer-events: none;
        transition: border-color 0.5s ease-in-out;
      "></div>
    </div>
  `
}

// 状态相关函数
const getStatusClass = (station: any) => {
  return store.getStationStatus(station)
}

const getStatusText = (station: any) => {
  const status = store.getStationStatus(station)
  const statusMap = {
    free: '空闲',
    busy: '繁忙', 
    maintenance: '维护中'
  }
  return statusMap[status] || '未知'
}

// 定位用户
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const locateUser = (event?: Event | number) => {
  // 如果传入的是Event对象，则使用默认重试次数
  const retryCount = typeof event === 'number' ? event : 0;
  if (!map.value || !AMap.value) return
  
  console.log('📍 开始定位用户位置...')
  
  // 使用高德地图的定位服务
  const geolocation = new AMap.value.Geolocation({
    enableHighAccuracy: true, // 高精度定位
    timeout: 15000, // 增加超时时间，给高精度定位更多机会
    maximumAge: 0, // 位置缓存时间
    convert: true, // 坐标转换
    showButton: true, // 显示定位按钮
    showMarker: true, // 显示定位点
    showCircle: true, // 显示定位精度范围
    panToLocation: true, // 定位成功后自动移动地图到定位点
    zoomToAccuracy: true, // 定位成功后自动缩放地图到合适级别
    extensions: 'all', // 尝试获取更详细的定位信息
    noIpLocate: 0, // 0: 可以使用IP定位 1: 不使用IP定位
    noGeoLocation: 0 // 0: 可以使用浏览器定位 1: 不使用浏览器定位
  })
  
  // 添加定位监听
  geolocation.getCurrentPosition((status: string, result: any) => {
    if (status === 'complete') {
      // 记录详细的定位信息，包括精度评估
      console.log('✅ 定位成功:', {
        position: result.position,
        accuracy: result.accuracy || '未知', // 定位精度（米）
        location_type: result.location_type || '未知', // 定位方式
        formatted_address: result.formattedAddress || '未知' // 格式化地址
      })
      
      // 保存用户位置到 store
      const lng = result.position.lng
      const lat = result.position.lat
      const userLngLat = [lng, lat]
      store.setUserLocation(lng, lat)
      
      // 移动地图到用户位置
      map.value.setZoomAndCenter(15, userLngLat, true)
      
      // 添加定位标记，显示精度信息
      const marker = new AMap.value.Marker({
        position: userLngLat,
        content: `
          <div style="
            width: 20px;
            height: 20px;
            background: #1890ff;
            border: 3px solid white;
            border-radius: 50%;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
            animation: pulse 1s infinite;
          ">
          </div>
          <div style="
            position: absolute;
            bottom: -25px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 10px;
            white-space: nowrap;
          ">
            精度: ${result.accuracy || '未知'}m
          </div>
          <style>
            @keyframes pulse {
              0% { box-shadow: 0 2px 8px rgba(0,0,0,0.3); }
              50% { box-shadow: 0 0 0 10px rgba(24, 144, 255, 0.3); }
              100% { box-shadow: 0 2px 8px rgba(0,0,0,0.3); }
            }
          </style>
        `,
        offset: new AMap.value.Pixel(-10, -10)
      })
      
      // 清除之前的定位标记
      if (userLocationMarker.value) {
        map.value.remove(userLocationMarker.value)
      }
      
      userLocationMarker.value = marker
      map.value.add(marker)
      
      // 添加定位精度圈
      if (result.accuracy && result.accuracy > 0) {
        // 如果已有精度圈则移除
        if ((window as any).accuracyCircle) {
          map.value.remove((window as any).accuracyCircle)
        }
        
        // 创建新的精度圈
        const circle = new AMap.value.Circle({
          center: userLngLat,
          radius: result.accuracy, // 定位精度半径（米）
          strokeColor: '#1890ff',
          strokeOpacity: 0.3,
          fillColor: '#1890ff',
          fillOpacity: 0.1,
          strokeWeight: 1
        })
        
        circle.setMap(map.value)
        (window as any).accuracyCircle = circle
      }
      
      // 重新计算充电站距离并显示
      if (userLngLat && Array.isArray(userLngLat) && userLngLat.length === 2 && typeof userLngLat[0] === 'number' && typeof userLngLat[1] === 'number') {
        updateStationsDistance([userLngLat[0], userLngLat[1]] as [number, number])
      } else {
        console.warn('⚠️ 用户位置格式不正确，跳过距离计算')
      }
    } else {
      console.error('❌ 定位失败:', result.message)
      
      // 实现重试机制，最多重试2次
      if (retryCount < 2) {
        console.log(`🔄 正在进行第${retryCount + 1}次重试...`)
        // 延迟2秒后重试
        setTimeout(() => {
          locateUser(Number(retryCount + 1))
        }, 2000)
        return
      }
      
      // 所有重试都失败后，回退到默认位置
      map.value.setZoomAndCenter(15, mapConfig.center, true)
      alert('定位失败，已定位到默认位置。请检查位置权限设置和网络连接。')
    }
  })
}

// 放大
const zoomIn = () : void => {
  if (map.value) {
    const currentZoom = map.value.getZoom()
    map.value.setZoom(currentZoom + 1)
  }
}

// 缩小
const zoomOut = () : void => {
  if (map.value) {
    const currentZoom = map.value.getZoom()
    map.value.setZoom(currentZoom - 1)
  }
}

// 计算距离
const calculateDistance = (from: [number, number], to: [number, number]): number => {
  if (!AMap.value) return 0
  const distance = AMap.value.GeometryUtil.distance(from, to)
  return Math.round(distance)
}

// 格式化距离显示 - 暂时移除未使用的函数
// 如果将来需要，可以取消注释这段代码
/*
const formatDistance = (distance: number): string => {
  if (distance < 1000) {
    return `${distance}米`
  } else {
    return `${(distance / 1000).toFixed(1)}公里`
  }
}
*/

// 更新充电站距离
const updateStationsDistance = (userLocation: [number, number]) : void => {
  if (!store.stations || store.stations.length === 0) return
  
  // 更新每个充电站的距离
  store.stations.forEach((station: any) => {
    const stationLocation = [station.lng, station.lat] as [number, number]
    station.distance = calculateDistance(userLocation, stationLocation)
  })
  
  console.log('📏 已更新所有充电站距离', (store.stations && store.stations.length) || 0, '个充电站')
}



// 清除标记
const clearMarkers = () => {
  // 清理普通标记
  if (markers.value.length > 0) {
    console.log(`🧹 清理${markers.value.length}个标记`)
    map.value?.remove(markers.value)
    markers.value = []
  }
  
  // 清理定位标记
  if (userLocationMarker.value) {
    map.value?.remove(userLocationMarker.value)
    userLocationMarker.value = null
  }
  
  // 清理聚合标记
  if (cluster.value) {
    console.log('🧹 清理聚合实例')
    // 移除聚合实例而不是调用不存在的clearMarkers方法
    if (map.value) {
      // 直接将聚合器从地图中移除
      cluster.value = null
    }
  }
  
  // 清理Spiderfy标记
  clearSpiderfyMarkers()
  
  // 清理已显示标记映射
  visibleMarkersMap.forEach((marker) => {
    if (marker && map.value) {
      map.value.remove(marker)
    }
  })
  visibleMarkersMap.clear()
  
  // 清理定时任务
  if (markersBatchRenderTimer !== null) {
    clearTimeout(markersBatchRenderTimer)
    markersBatchRenderTimer = null
  }
  
  // 重置渲染状态
  isRendering = false
}

// 组件挂载
onMounted(() => {
  console.log('📦 地图组件挂载')
  initMap()
})

// 组件卸载
onUnmounted(() => {
  console.log('🗑️ 地图组件卸载')
  if (map.value) {
    map.value.destroy()
  }
  clearMarkers()
  if (cluster.value) {
    cluster.value.setMap(null)
  }
})

// 监听充电站数据变化
watch(() => store.stations, (newStations) => {
  console.log('🔄 充电站数据变化:', newStations?.length)
  if (newStations && newStations.length > 0 && map.value && AMap.value) {
    createStationMarkers()
  }
}, { deep: true, immediate: true })
</script>

<style>
/* 全局动画关键帧定义 */
@keyframes pulse-free {
  0% {
    box-shadow: 0 0 0 0 rgba(82, 196, 26, 0.7);
    transform: scale(1);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(82, 196, 26, 0);
    transform: scale(1.05);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(82, 196, 26, 0);
    transform: scale(1);
  }
}

@keyframes pulse-busy {
  0% {
    box-shadow: 0 0 0 0 rgba(250, 140, 22, 0.7);
    transform: scale(1);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(250, 140, 22, 0);
    transform: scale(1.05);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(250, 140, 22, 0);
    transform: scale(1);
  }
}

@keyframes pulse-maintenance {
  0% {
    box-shadow: 0 0 0 0 rgba(245, 34, 45, 0.7);
    transform: scale(1);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(245, 34, 45, 0);
    transform: scale(1.05);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(245, 34, 45, 0);
    transform: scale(1);
  }
}

/* 自定义标记过渡效果 */
.custom-marker {
  transition: all 0.5s ease-in-out !important;
}
</style>

<style scoped>
.amap-container {
  position: relative;
  width: 100%;
  height: 600px;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e8e8e8;
  background: #f5f5f5;
}

.map-container {
  width: 100%;
  height: 100%;
}

.map-loading, .map-error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.95);
  z-index: 1000;
  border-radius: 8px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.retry-btn {
  margin-top: 12px;
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.retry-btn:hover {
  background: #40a9ff;
}

/* 地图控件 */
.map-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  z-index: 999;
}

.control-btn {
  width: 44px;
  height: 44px;
  background: white;
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  transition: all 0.3s ease;
}

.control-btn:hover {
  background: #f0f2f5;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}

/* 信息窗口 */
.info-window {
  position: absolute;
  width: 300px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  z-index: 1000;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
}

.info-header h4 {
  margin: 0;
  font-size: 16px;
  color: #1890ff;
}

.info-content {
  padding: 16px;
}

.address {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.status-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.free {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-badge.busy {
  background: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.status-badge.maintenance {
  background: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.charger-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  color: #333;
}

.price {
  font-size: 18px;
  font-weight: 600;
  color: #ff4d4f;
  margin-bottom: 12px;
  text-align: center;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.nav-btn, .detail-btn {
  flex: 1;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.nav-btn {
  background: #1890ff;
  color: white;
}

.nav-btn:hover {
  background: #40a9ff;
}

.detail-btn {
  background: #f0f2f5;
  color: #333;
}

.detail-btn:hover {
  background: #e0e2e5;
}

.amap-btn {
  background: #ff6b00;
  color: white;
}

.amap-btn:hover {
  background: #ff8833;
}

/* 路线信息面板 */
.route-info-panel {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 280px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  z-index: 998;
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
}

.route-header h4 {
  margin: 0;
  font-size: 16px;
  color: #1890ff;
}

.route-content {
  padding: 16px;
}

.route-detail {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.route-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.route-item .label {
  color: #666;
  font-size: 14px;
}

.route-item .value {
  font-weight: 500;
  color: #333;
}

.start-nav-btn {
  width: 100%;
  padding: 10px 16px;
  background: #52c41a;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background 0.3s;
}

.start-nav-btn:hover {
  background: #73d13d;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
  background: #f5f5f5;
  border-radius: 50%;
}
</style>

<style>
/* 标记动画 */
.custom-marker {
  transition: all 0.3s ease !important;
}

.custom-marker.free {
  animation: pulse-free 2s infinite;
}

.custom-marker.busy {
  animation: pulse-busy 3s infinite;
}

.custom-marker.maintenance {
  animation: none;
  opacity: 0.7;
}

.custom-marker:hover {
  transform: scale(1.2) !important;
  z-index: 1000 !important;
}

@keyframes pulse-free {
  0% {
    box-shadow: 0 0 0 0 rgba(82, 196, 26, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(82, 196, 26, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(82, 196, 26, 0);
  }
}

@keyframes pulse-busy {
  0% {
    box-shadow: 0 0 0 0 rgba(250, 140, 22, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(250, 140, 22, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(250, 140, 22, 0);
  }
}
</style>